package com.arvin.faceDetect.utils

import android.graphics.Bitmap
import android.util.Log
import android.util.LruCache
import com.google.mlkit.vision.face.Face

object PreprocessCache {
    private const val TAG = "PreprocessCache"
    private const val MAX_CACHE_SIZE = 20
    private const val CACHE_TIMEOUT = 100L // 100ms内复用结果

    private val cache = object : LruCache<String, CachedBitmap>(MAX_CACHE_SIZE) {
        override fun entryRemoved(
            evicted: Boolean,
            key: String,
            oldValue: CachedBitmap,
            newValue: CachedBitmap?
        ) {
            if (evicted) {
                BitmapPool.recycleBitmap(oldValue.bitmap)
            }
        }

        override fun sizeOf(key: String, value: CachedBitmap): Int {
            return 1
        }
    }

    fun get(key: String): Bitmap? {
        val cached = cache.get(key)
        return if (cached != null && !isExpired(cached.timestamp)) {
            Log.d(TAG, "命中缓存: $key")
            cached.bitmap
        } else {
            Log.d(TAG, "缓存未命中或已过期: $key")
            null
        }
    }

    fun put(key: String, bitmap: Bitmap) {
        cache.put(key, CachedBitmap(bitmap, System.currentTimeMillis()))
        Log.d(TAG, "存入缓存: $key")
    }

    fun generateKey(face: Face, timestamp: Long): String {
        return "${face.trackingId}_${timestamp / CACHE_TIMEOUT}"
    }

    private fun isExpired(timestamp: Long): Boolean {
        return System.currentTimeMillis() - timestamp > CACHE_TIMEOUT
    }

    fun clear() {
        cache.evictAll()
        Log.d(TAG, "清空预处理缓存")
    }

    private data class CachedBitmap(
        val bitmap: Bitmap,
        val timestamp: Long
    )
} 